package com.dap.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wangmin on 2017/9/20.
 */
public abstract class SinaShortUrl {
    private static final Logger logger = LoggerFactory.getLogger(SinaShortUrl.class);


    private static MyHttpClient shortUrlHttpClient = new MyHttpClient();
    /**
     * 生成短链接
     *
     * @author: wangmin
     * 例子:
     * http://api.t.sina.com.cn/short_url/shorten.json?source=3271760578&url_long=http://www.douban.com/note/249723561/
     */
    public static String generateShortUrl(String url) {
        try {
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("source", "3271760578"));
            params.add(new BasicNameValuePair("url_long", url));
            String jsonStr = shortUrlHttpClient.post("http://api.t.sina.com.cn/short_url/shorten.json", params);

            JSONArray jsonArray = JSONObject.parseArray(jsonStr.replace("\\", ""));

            JSONObject firstShortResult = (JSONObject) jsonArray.get(0);
            return firstShortResult.getString("url_short");
        } catch (Exception e) {
            logger.info("", e);
            return null;
        }
    }

    public static void main(String[] args) throws Exception {
        long firstRequestStartTime = System.currentTimeMillis();
        String shortUrl = generateShortUrl("http://write.blog.csdn.net/postlist");
        long firstRequestEndTime = System.currentTimeMillis();
        System.out.println("短链接 = " + shortUrl);
        System.out.println("第一次请求消耗时间 = " + (firstRequestEndTime - firstRequestStartTime) + "ms\n\n\n\n\n");

        for (int i = 0; i < 100; ++i) {
            generateShortUrl("http://write.blog.csdn.net/postlist");
        }
        System.out.println("100 = " + (System.currentTimeMillis() - firstRequestEndTime) + "ms\n\n\n\n\n");
    }
}
